<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{ updataFull, updataDialogWidth }"
      :fullscreen="isfullscreen"
      :width="setDialogWidth('850px')"
      :append-to-body="true"
      :visible="visible"
      :title="title"
      @open="open"
      @close="close(false)"
    >
      <el-form
        ref="form"
        label-width="100px"
        :model="form"
        :rules="rules"
        class="flex flex-wrap pr-30"
      >
        <el-form-item
          v-if="form.parentId !== '0' && form.operateType !== 'GIS'"
          :label="$t('PARENT_NAME')"
          class="w-50"
        >
          {{ getParentName(form.parentId) }}
        </el-form-item>
        <el-form-item
          v-if="form.operateType && form.operateType === 'GIS'"
          :label="$t('BELONGS_REGION_NAME')"
          class="w-50"
          prop="parentId"
        >
          <region-cascader
            :data-name="'areaTree'"
            :selected-ids="[form.parentId]"
            :placeholder="$t('PLEASE_SELECT_REGION')"
            @change="regionChange"
          />
        </el-form-item>
        <el-form-item class="w-50" :label="$t('CATEGORY')">
          <el-select
            v-model="form.regionType"
            :disabled="
              (form.operateType && form.operateType === 'GIS') ||
                regionTypeDisabled ||
                type !== 'add' ||
                form.regionType === 'ROOM' ||
                form.parentId === '0'
            "
          >
            <template v-if="form.regionType === 'ROOM'">
              <el-option :label="$t('ROOM')" value="ROOM" />
            </template>
            <template v-else>
              <el-option :label="$t('REGION')" value="REGION" />
              <el-option :label="$t('STATION')" value="STATION" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.parentId === '0'" class="w-50" />
        <!-- <el-form-item v-if="form.regionType === 'STATION' && form.virtualFlag" class="w-50" /> -->
        <el-form-item
          class="w-50"
          :label="regionTypeName[form.regionType] + $t('NAME')"
          prop="regionName"
        >
          <el-input
            v-model.trim="form.regionName"
            maxlength="50"
            :readonly="type === 'view'"
            :placeholder="$t('PLEASE_INPUT') + regionTypeName[form.regionType] + $t('NAME')"
          />
        </el-form-item>
        <el-form-item
          v-if="(form.regionType === 'STATION' && !form.virtualFlag) || form.regionType === 'ROOM'"
          class="w-50"
          :label="regionTypeName[form.regionType] + $t('STATE')"
          :readonly="type === 'view'"
        >
          <el-select v-model="form.status" :disabled="type === 'view'">
            <el-option
              v-for="item in dictList.REGION_STATUS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="codeNameObj[form.regionType]" class="w-50" prop="regionId">
          <el-input
            v-model="form.regionId"
            :readonly="type !== 'add'"
            maxlength="32"
            :placeholder="$t('REGION_SOURCE_CODE_PLACEHOLDER')"
          />
        </el-form-item>
        <el-form-item class="w-50" :label="$t('CONTACT_PERSON')">
          <el-input v-model="form.person" :readonly="type === 'view'" maxlength="32" />
        </el-form-item>
        <el-form-item class="w-50" :label="$t('CONTACT_NUMBER')" prop="tel">
          <el-input v-model="form.tel" :readonly="type === 'view'" />
        </el-form-item>
        <el-form-item class="w-50" :label="$t('EMAIL')" prop="email">
          <el-input v-model="form.email" :readonly="type === 'view'" maxlength="50" />
        </el-form-item>
        <el-form-item class="w-50" :label="$t('CONTACTADDRESS')">
          <el-input v-model.trim="form.address" :readonly="type === 'view'" maxlength="32" />
        </el-form-item>
        <div class="w-100 flex location">
          <div class="w-50 flex align-center">
            <div class="location-label">{{ $t('GEOGRAPHIC_LOCATION') }}</div>
            <el-form-item class="flex-1 flex lat location-input" prop="longitude" label-width="0px">
              <div class="flex align-center">
                <span class="no-wrap mr-10">{{ $t('LONGITUDE') }}</span>
                <el-input v-model="form.longitude" :readonly="type === 'view'" />
              </div>
            </el-form-item>
          </div>
          <div class="w-50 flex flex-1 align-center">
            <el-form-item class="flex-1 location-input" :label="$t('LATITUDE')" prop="latitude">
              <el-input v-model="form.latitude" :readonly="type === 'view'" />
            </el-form-item>
            <i
              type="text"
              class="el-icon-location-outline p-5 font-larger pointer"
              @click="showLoacte"
            />
          </div>
        </div>
        <el-form-item class="w-100" :label="$t('DESCRIPTION')">
          <el-input
            v-model="form.description"
            :readonly="type === 'view'"
            type="textarea"
            :row="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <template v-if="type === 'view'">
          <el-button @click="close(false)">{{ $t('CLOSE') }}</el-button>
        </template>
        <template v-else>
          <el-button @click="close(false)">{{ $t('CANCEL') }}</el-button>
          <el-button type="primary" @click="$debounce(save)">{{ $t('SAVE') }}</el-button>
        </template>
      </template>
    </el-dialog>
    <locate
      v-if="visible"
      :visible="locateShow"
      :is-mod="type != 'view'"
      :operate-type="type"
      :data="form"
      @close="locateClose"
    />
  </div>
</template>

<script>
  import { mapGetters, mapMutations } from 'vuex'
  import { changeDecimal } from '@/utils/common'
  import regionApi from '@/api/basebiz/RegionApi'
  import OrgRegionApi from '@/api/basebiz/OrgRegionApi'
  import Locate from './Locate'
  import RegionCascader from '@/components/RegionCascader'
  export default {
    components: { Locate, RegionCascader },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      isHome: {
        type: Boolean,
        default: false
      },
      data: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        locateShow: false,
        form: {},
        codeNameObj: {
          REGION: this.$t('REGION_CODE'),
          STATION: this.$t('STATION_CODE'),
          ROOM: this.$t('EQUIPMENT_ROOM_CODE')
        },
        regionTypeName: {
          REGION: this.$t('REGION'),
          STATION: this.$t('STATION'),
          ROOM: this.$t('ROOM')
        },
        regionTypeDisabled: false
      }
    },
    inject: ['functionName'],
    computed: {
      ...mapGetters(['dictList', 'getOrg', 'regionTree', 'baseRegionList', 'stationSelected']),
      ...mapMutations(['SET_STATION_INFO']),
      title() {
        const firstName = {
          add: this.$t('ADD'),
          view: this.$t('VIEW'),
          mod: this.$t('MOD')
        }
        return firstName[this.type] + this.regionTypeName[this.form.regionType]
      },
      rules() {
        return {
          parentId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT_REGION'),
              trigger: ['change', 'blur']
            }
          ],
          regionName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('NAME'),
              trigger: 'blur'
            }
          ],
          regionId: [
            {
              pattern: /^[a-zA-Z0-9]+$/,
              message: this.$t('REGION_CODE_FORMAT_INCORRECT'), // '区域编号格式错误',
              trigger: 'blur'
            }
          ],
          tel: [
            {
              required: false,
              validator: (rule, value, callback) => {
                if (value !== '') {
                  const mobile = /^1[3456789]\d{9}$/
                  const phone = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/
                  if (!mobile.test(value) && !phone.test(value)) {
                    callback(this.$t('PHONE_NUMBER_FORMAT_INCORRECT')) // '电话号码格式错误',
                  } else {
                    callback()
                  }
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          email: [
            {
              pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              message: this.$t('EMAIL_FORMAT_WRONG'), // '电子邮箱格式错误',
              trigger: 'blur'
            }
          ],
          longitude: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(this.$t('PLEASE_ENTER_LONGITUDE'))
                } else {
                  const regLng =
                    /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/
                  if (regLng.test(value)) {
                    callback()
                  } else {
                    callback(this.$t('LONGITUDE_REG'))
                  }
                }
              },
              trigger: ['blur', 'change']
            }
          ],
          latitude: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(this.$t('PLEASE_ENTER_LATITUDE'))
                } else {
                  const regLat = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/
                  if (regLat.test(value)) {
                    callback()
                  } else {
                    callback(this.$t('LATITUDE_REG'))
                  }
                }
              },
              trigger: ['blur', 'change']
            }
          ]
        }
      }
    },
    methods: {
      defaultData() {
        return {
          parentId: '0',
          regionName: '',
          person: '',
          tel: '',
          email: '',
          address: '',
          regionType: 'REGION',
          status: 'PROJECT',
          longitude: '',
          latitude: '',
          description: ''
        }
      },
      open() {
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate()
        })
        this.regionTypeDisabled = false
        this.form = {
          ...this.defaultData(),
          ...this.data
        }
        if (this.type === 'add') {
          this.regionTypeDisabled = this.form.regionTypeDisabled
        }
      },
      showLoacte() {
        if (!this.form.longitude && !this.form.latitude) {
          this.locateShow = true
          return
        }
        const checkArr = []
        this.form.longitude && checkArr.push('longitude')
        this.form.latitude && checkArr.push('latitude')
        let locateShow = true
        this.$refs.form.validateField(checkArr, valid => {
          locateShow = locateShow && !valid
        })
        this.locateShow = locateShow
      },
      save() {
        this.$refs.form.validate(valid => {
          if (!valid) {
            console.log(valid)
            return false
          }
          const requstData = { ...this.form, functionName: this.functionName }
          delete requstData.status
          if (this.form.regionType === 'REGION') {
            requstData.orgId = this.getOrg.orgId
          } else {
            requstData.status = this.form.status
          }
          this.handleRegion(requstData)
        })
      },
      // 新增、修改区域
      handleRegion(requstData) {
        if (this.type === 'add') {
          regionApi.add(requstData).then(res => {
            this.$message.success(this.$t('ADD_SUCCESS'))
            if (res) {
              // 找到新增的区域或站点的regionId
              regionApi
                .find({ parentId: requstData.parentId, keyword: requstData.regionName })
                .then(res => {
                  if (res) {
                    // 当前用户绑定该区域
                    OrgRegionApi.add({
                      orgId: this.getOrg.orgId,
                      regionId: res.regionId,
                      selected: true
                    }).then(res => {
                      this.close(true)
                    })
                    this.form.regionId = res.regionId // gis里需要，新增的站点根据这个regionId来单芯新增站点
                  }
                })
            }
          })
        } else {
          regionApi.mod(requstData).then(res => {
            this.$message.success(this.$t('MODIFY_SUCCESS'))
            this.close(true)
          })
        }
      },
      close(load) {
        this.regionTypeDisabled = false
        this.$emit('close', { ...this.form, load })
        if (this.functionName === 'region' && load) {
          // 需要把修改，新增，删除的站点对象传递出去，方便gis里监听到此站点的改变
          this.$store.commit('SET_STATION_INFO', { ...this.form, load, type: this.type })
        }
      },
      locateClose(point) {
        this.locateShow = false
        this.$store.commit(
          'setStationSelected',
          this.stationSelected.filter(i => i !== 'newRegion')
        )
        if (point && point.longitude && point.latitude) {
          this.form.longitude = changeDecimal(point.longitude, 6)
          this.form.latitude = changeDecimal(point.latitude, 6)
        }
      },
      regionChange(data) {
        this.form.parentId = data
      },
      deepSearch(data, key, childKey, keywords) {
        const baseData = JSON.parse(JSON.stringify(data))
        let current = []
        baseData.forEach(item => {
          if (!current.length && item[childKey] && item[childKey].length > 0) {
            current = this.deepSearch(item[childKey], key, childKey, keywords)
          }
          if (item[key].indexOf(keywords) !== -1) {
            current.push(item)
          }
        })
        return current
      },
      getParentName(parentId) {
        const parentData = this.baseRegionList.find(i => i.regionId === parentId)
        return parentData ? parentData.regionName : ''
      }
    }
  }
</script>

<style lang="scss">
  .location {
    margin-bottom: 18px;
    .location-label {
      width: 100px;
      padding: 0 12px 0 0;
      line-height: 28px;
      text-align: right;
    }
    .lat {
      .el-form-item__content {
        flex: 1;
      }
    }
    .location-input .el-form-item__label::before {
      content: '' !important;
      margin: 0 !important;
    }
    .el-input__inner {
      text-align: left;
    }
    .el-form-item--mini.el-form-item,
    .el-form-item--small.el-form-item {
      margin-bottom: 0;
    }
  }
</style>
